package com.atguigu.tingshu.account.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.account.mapper.UserAccountDetailMapper;
import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.model.account.UserAccount;
import com.atguigu.tingshu.model.account.UserAccountDetail;
import com.atguigu.tingshu.vo.account.AccountDeductVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Map;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements UserAccountService {

    @Autowired
    private UserAccountMapper userAccountMapper;

    @Autowired
    private UserAccountDetailMapper userAccountDetailMapper;

    /**
     * 用户首次注册成功后，为用户初始账户余额记录
     *
     * @param map 消息对象 包含：用户ID，赠送体验金额，标题，订单编号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void initUserAccount(Map<String, Object> map) {
        //1.新增账户记录
        Long userId = (Long) map.get("userId");
        BigDecimal amount = (BigDecimal) map.get("amount");
        String title = (String) map.get("title");
        String orderNo = (String) map.get("orderNo");
        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(userId);
        userAccount.setTotalAmount(amount);
        userAccount.setAvailableAmount(amount);
        userAccount.setTotalIncomeAmount(amount);
        userAccount.setLockAmount(new BigDecimal("0.00"));
        userAccount.setTotalPayAmount(new BigDecimal("0.00"));
        userAccountMapper.insert(userAccount);

        //2.新增账户变动日志
        this.saveUserAccountDetail(userId, title, SystemConstant.ACCOUNT_TRADE_TYPE_DEPOSIT, amount, orderNo);
    }

    /**
     * 新增账户变动日志
     *
     * @param userId    用户ID
     * @param title     内容
     * @param tradeType 交易类型 1201-充值 1202-锁定 1203-解锁 1204-消费',
     * @param amount    金额
     * @param orderNo   订单编号
     */
    @Override
    public void saveUserAccountDetail(Long userId, String title, String tradeType, BigDecimal amount, String orderNo) {
        UserAccountDetail userAccountDetail = new UserAccountDetail();
        userAccountDetail.setUserId(userId);
        userAccountDetail.setTitle(title);
        userAccountDetail.setTradeType(tradeType);
        userAccountDetail.setAmount(amount);
        userAccountDetail.setOrderNo(orderNo);
        userAccountDetailMapper.insert(userAccountDetail);
    }

    /**
     * 获取用户可用余额
     *
     * @param userId
     * @return
     */
    @Override
    public BigDecimal getAvailableAmount(Long userId) {
        UserAccount userAccount = userAccountMapper.selectOne(
                new LambdaQueryWrapper<UserAccount>()
                        .eq(UserAccount::getUserId, userId)
        );
        Assert.notNull(userAccount, "用户账户不存在！");
        return userAccount.getAvailableAmount();
    }

    /**
     * 检查扣减账户余额
     * 避免账户余额超扣，采用分布式锁；数据库锁（悲观锁或乐观锁）
     *
     * @param accountDeductVo
     */
    @Override
    //@Transactional(rollbackFor = Exception.class) //TODO 引入Seata一定要去掉,否则会导致分布式事务失效
    public void deduct(AccountDeductVo accountDeductVo) {
        //1.采用数据库悲观锁，检查账户余额是否满足扣款需求
        BigDecimal amount = accountDeductVo.getAmount();
        Long userId = accountDeductVo.getUserId();
        UserAccount userAccount = userAccountMapper.checkDeduction(userId, amount);
        if (userAccount == null) {
            throw new GuiguException(500, "账户余额不足！");
        }
        //2.扣减账户余额
        userAccountMapper.update(
                null,
                new LambdaUpdateWrapper<UserAccount>()
                        .eq(UserAccount::getUserId, userId)
                        .setSql("total_amount = total_amount -" + amount)
                        .setSql("available_amount = available_amount -" + amount)
                        .setSql("total_pay_amount = total_pay_amount +" + amount)
                );
        //3.新增账户变动日志
        this.saveUserAccountDetail(accountDeductVo.getUserId(), accountDeductVo.getContent(), SystemConstant.ACCOUNT_TRADE_TYPE_MINUS, accountDeductVo.getAmount(), accountDeductVo.getOrderNo());
    }

    /**
     * 查询账户变动日志（消费、充值）
     * @param pageParam 分页参数
     * @param userId 用户ID
     * @param tradeType 交易类型1201-充值 1202-锁定 1203-解锁 1204-消费
     * @return
     */
    @Override
    public Page<UserAccountDetail> getUserAccountDetailPage(Page<UserAccountDetail> pageParam, Long userId, String tradeType) {
        LambdaQueryWrapper<UserAccountDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserAccountDetail::getUserId, userId);
        queryWrapper.eq(UserAccountDetail::getTradeType, tradeType);
        queryWrapper.orderByDesc(UserAccountDetail::getCreateTime);
        return userAccountDetailMapper.selectPage(pageParam, queryWrapper);
    }
}
